package com.example.weather;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weather.model.Constants;
import com.example.weather.model.PlaceResponse;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class PlaceAdapter extends RecyclerView.Adapter<PlaceViewHolder> {

    private List<PlaceResponse.Place> placeList = new ArrayList<>();
    private final Activity context;

    public PlaceAdapter(Activity context) {
        this.context = context;
    }

    public void setList(List<PlaceResponse.Place> placeList) {
        this.placeList = placeList;
        notifyDataSetChanged();
    }

    public void clearData() {
        this.placeList.clear();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public PlaceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PlaceViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.place_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull PlaceViewHolder holder, int position) {
        //获取对应item的数据
        PlaceResponse.Place place = placeList.get(position);
        //绑定数据
        holder.bindData(place);
        //设置view的点击事件
        holder.itemView.setOnClickListener(v-> {
            //跳转天气页面
            if (context != null) {
                Intent intent = new Intent(context, WeatherActivity.class);
                //将place信息填入intent内
                intent.putExtra(Constants.WEATHER, new Gson().toJson(place));
                context.startActivity(intent);
                context.finish();

            }
        });
    }

    @Override
    public int getItemCount() {
        return placeList.size();
    }
}

class PlaceViewHolder extends RecyclerView.ViewHolder {

    private final TextView placeName, placeAddress;

    public PlaceViewHolder(@NonNull View itemView) {
        super(itemView);
        placeName = itemView.findViewById(R.id.placeName);
        placeAddress = itemView.findViewById(R.id.placeAddress);
    }

    public void bindData(PlaceResponse.Place place) {
        placeName.setText(place.getName());
        placeAddress.setText(place.getAddress());
    }
}